package org.biogroovy.io.local

import groovy.xml.MarkupBuilder

import org.biogroovy.io.AbsWriter;
import org.biogroovy.search.Search
import org.biogroovy.search.SearchParam
import org.biogroovy.search.SearchResult


/**
 * This class is responsible for writing a search out to a file.
 *
 */
class SearchWriter extends AbsWriter<Search> {
	
	public SearchWriter(){
		super("search.xml");
	}

	@Override
	public void write(Search search, OutputStream out) throws IOException {
		MarkupBuilder builder = new MarkupBuilder(new PrintWriter(out));
		createXML(builder, search);
	}

	@Override
	public void writeCollection(Collection<Search> searches, OutputStream out)
			throws IOException {
				
		MarkupBuilder builder = new MarkupBuilder(new PrintWriter(out));
		builder.searches{
			searches.each{Search src ->
				createXML(builder, src)
			}
		}
		
	}

	@Override
	protected void createXML(MarkupBuilder builder, Search src) {
				
		
		builder.search(name:src.name, lastExecuted: src.getLastExecutedAsString(), searchEngineName:src.searchEngineName){
			searchParams(){
				src.searchParams.parameters.each{SearchParam param ->
					searchParam(name:param.name, dataName:param.dataName, isEditable:param.isEditable, isRequired:param.isRequired, isSubTerm:param.isSubTerm, isTerm:param.isTerm, hint:param.hint, value:param.value, paramType:param.paramType.name() );
					
				}
			}
			delegate.searchResults(){
				src.results.each{SearchResult result ->
					delegate.result(accession: result.accession, description:result.description, title:result.title, url:result.url){
						result.tags.each{String tag ->
							delegate.tag(name:tag)
						}
					}
				}
			}
		}
		
	}



}
